package com.kaifamiao.wendao.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@WebServlet( "/image/upload" )
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {

    private String location ;

    @Override
    public void init() throws ServletException {
        // this 是 ImageUploadServlet 类型的实例
        // ImageUploadServlet 的直接父类 HttpServlet 继承了 GenericServlet
        // 而 GenericServlet 实现了 Servlet 和 ServletConfig 接口
        ServletContext application = this.getServletContext();
        location = application.getInitParameter( "imageStoreLocation" );
        System.out.println( location );
    }

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        Part part = request.getPart( "upFile" );
        System.out.println( part );

        String filename = part.getSubmittedFileName();

        Map<String,Object> map = new HashMap<>();

        try {
            InputStream in = part.getInputStream();
            // 一次性读取流中所有可读字节(适用于读取小文件中的内容)
            byte[] bytes = in.readAllBytes(); // Java 9 开始提供的方法
            File target = new File( location , filename );
            OutputStream out = new FileOutputStream(target);
            // 一次性将所有字节写入到文件输出流
            out.write(bytes);
            out.close();
            in.close();
            // result = "{ \"success\" : true , \"file_path\" : \"/image/show?filename=" + filename + "\"}";
            map.put( "success" , true );
            map.put( "file_path" , "/image/show/" + filename );
        } catch ( IOException e ) {
            // result = "{ \"success\" : false , \"msg\" : \"文件上传失败\"}";
            map.put( "success" , false );
            map.put( "msg" , "文件上传失败" );
        }

        Gson gson = new Gson();
        String result = gson.toJson( map );
        System.out.println( result );

        response.setContentType( "application/json" );
        //response.setContentType( "text/plain" );
        PrintWriter out = response.getWriter();
        out.println( result );

    }

}
